<template>
  <div class="upload-file" :class="filelist.length > limit ? 'hide' : ''">
    <image-explorer ref="imgRef" @get-files="getFiles" />

    <el-upload
      ref="uploadRef"
      slot="tip"
      accept="image/png,image/jpeg"
      :action="baseurl + 'base/upload'"
      :disabled="true"
      :file-list="filelist"
      :limit="limit"
      list-type="picture-card"
      multiple
      name="upload_image"
      :on-success="OnSuccess"
    >
      <el-icon @click="getFilesDialog"><plus /></el-icon>
      <!-- <el-icon><Plus /></el-icon> -->

      <template #file="{ file }">
        <div>
          <img alt="" class="el-upload-list__item-thumbnail" :src="file.url" />
          <span class="el-upload-list__item-actions">
            <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
              <el-icon><zoom-in /></el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleDownload(file)">
              <el-icon><download /></el-icon>
            </span>
            <span v-if="!disabled" class="el-upload-list__item-delete" @click="handleRemove(file)">
              <el-icon><delete /></el-icon>
            </span>
          </span>
        </div>
      </template>
    </el-upload>

    <el-dialog v-model="dialogVisible">
      <img alt="Preview Image" :src="dialogImageUrl" w-full />
    </el-dialog>
  </div>
</template>
<script lang="ts" setup>
//组建说明：本组建用于上传图片使用。
//出现打包后无法上传图片情况时候

//第一步：node_modules\mockjs\dist\mock.js
//搜索：this.custom.xhr = xhr，在其下面加上 MockXMLHttpRequest.prototype.upload = xhr.upload;
//第二步：\node_modules\mockjs\src\mock\xhr\xhr.js
//搜索：this.custom.xhr = xhr，在其下面加上 MockXMLHttpRequest.prototype.upload = xhr.upload;

const emit = defineEmits(['set-data', 'remove-data'])

defineOptions({
  name: 'UploadImageExplorer',
})

const props = defineProps({
  field: {
    //上传文件字段
    type: String,
    default: '',
  },
  limit: {
    //可上传数量
    type: Number,
    default: 1,
  },
  filelist: {
    //文件列表
    type: Array,
    default: [],
  },
})
import { Delete, Download, Plus, ZoomIn } from '@element-plus/icons-vue'
import { ref } from 'vue'

import { ElLoading, ElMessage, UploadFile } from 'element-plus'
import { api_upload_base64, api_upload_file } from '/@/api/files'
const baseurl = `${import.meta.env.VITE_APP_BASE_URL}`

//上传图片组建
const imgRef = ref<any>(null)
//上传图片组建，弹出
const getFilesDialog = (res: any) => {
  imgRef.value.showDialog()
  console.log('图片上传粘贴已移出')
  window.removeEventListener('paste', handlePaste)
}
//上传图片组建，获取到的结果使用
const getFiles = (res: any) => {
  console.log('获取结果', res)
  console.log('field', props.field)
  startPasteProcess()
  if (res) {
    emit('set-data', res, props.field)
  }
}
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const disabled = ref(false)

//移出图片
const handleRemove = (file: UploadFile) => {
  emit('remove-data', file, props.field)
}
//展示图片
const handlePictureCardPreview = (file: UploadFile) => {
  dialogImageUrl.value = file.url!
  dialogVisible.value = true
}
//下载图片
const handleDownload = (file: UploadFile) => {
  window.open(file.url, '_blank')
}

//---------------------------
//图片组建粘贴
const uploadRef = ref<any>(null)
//初始化粘贴准备
const startPasteProcess = () => {
  console.log('图片上传请粘贴内容')
  window.addEventListener('paste', handlePaste) // 监听粘贴事件
}
//粘贴操作
const handlePaste = (event: ClipboardEvent) => {
  const items = (event.clipboardData || (event as any).originalEvent.clipboardData).items

  if (!items || items.length === 0) {
    ElMessage({
      message: '当前浏览器不支持本地',
      type: 'error',
    })
    return
  }

  let file = ''
  // 搜索剪切板items
  for (let i = 0; i < items.length; i++) {
    if (items[i].type.indexOf('image') !== -1) {
      file = items[i].getAsFile()
      break
    }
  }
  if (!file) {
    // ElMessage({
    //   message: '粘贴内容非图片',
    //   type: 'warning',
    // })
    return
  }
  convertToBase64(file, (base64Str: any) => {
    uploadFile(base64Str)
  })
}
//粘贴转base64
const convertToBase64 = (file: any, callback: any) => {
  const reader = new FileReader()
  reader.onload = (event) => {
    callback(event.target.result)
  }
  reader.readAsDataURL(file)
}
//进行粘贴上传
const uploadFile = (base64Str: string) => {
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  console.log('上传前', base64Str)
  api_upload_base64({ img: base64Str }).then((res: any) => {
    console.log('上传后', res)
    loading.close()
    if (res.code == 200) {
      //表示上传成功，向files_file文件里插入
      api_upload_file(res).then((r: any) => {
        const arr = []
        arr.push(res)
        emit('set-data', arr, props.field)
      })
    }
  })
}
//粘贴准备
onMounted(() => {
  console.log('组件已显示')
  startPasteProcess()
})
//粘贴取消
onBeforeUnmount(() => {
  // 组件卸载时移除监听器
  console.log('已移出')
  window.removeEventListener('paste', handlePaste)
})
</script>
<style scoped lang="scss">
.upload-file .hide {
  :deep(.el-upload--picture-card) {
    display: none;
  }
}
</style>
